import 'package:contract_manager/models/contract_model.dart';
import 'package:get/get.dart';
import 'package:realm/realm.dart';

class ContractListController extends GetxController {
  final contracts = <Contract>[].obs;
  final isLoading = true.obs;
  late Realm realm;

  @override
  void onInit() {
    super.onInit();
    initRealm();
  }

  void initRealm() {
    realm = Realm(Configuration.local([Contract.schema]));
    loadContracts();
  }

  void loadContracts() {
    isLoading.value = true;
    try {
      final results = realm.all<Contract>();
      contracts.assignAll(results);
    } finally {
      isLoading.value = false;
    }
  }

  int getMaxId() {
    if (contracts.isEmpty) return 0;
    return contracts.map((c) => c.id).reduce((a, b) => a > b ? a : b);
  }

  Future<void> deleteContract(int id) async {
    try {
      final contract = realm.find<Contract>(id);
      if (contract != null) {
        realm.write(() {
          realm.delete(contract);
        });
        //contracts.removeWhere((c) => c.id == id);
        loadContracts();
      }
    } catch (e) {
      await Get.snackbar('错误', '删除合同失败');
    }

    Get.back();
  }

  @override
  void onClose() {
    realm.close();
    super.onClose();
  }
}
